import { defineStore } from 'pinia';
import { getUserInfoApi, getUserListApi, updateUserInfoApi, uploadUserAvatarApi } from '../../api/user';
import { ListParams, User } from '../../types/user';
import { ListResponse } from '../../types/common';

// 确保 ListResponse 类型定义正确

/**
 * 用户状态管理 Pinia Store
 * 包含用户信息、用户列表、加载状态等功能
 */
export const useUserStore = defineStore('user', {
    // 状态定义，返回一个对象
    state: () => ({
        user: {
            id: 0,
            username: '',
            password: '',
            age: 0,
            birth: '',
            gender: 1,
            signature: '',
            email: '',
            cellphone: '',
            avatarUrl: '',
            createdAt: '',
            updatedAt: '',
            deletedAt: '',
            isRemoved: 0,
            auth: {
                operate: [],
                route: []
            },
        } as User,
        userList: {
            total: 0,
            list: []
        } as ListResponse<User>,
        addedRoutes: false, // 是否已添加动态路由
        loading: false // 加载状态
    }),

    // 获取器，类似 Vuex 的 getters
    getters: {
        userinfo: (state) => state.user,
        isLoading: (state) => state.loading,
        userListData: (state) => state.userList.list,
        userTotal: (state) => state.userList.total,
        userRoles: (state) => state.user.auth.route,
        hasAddedRoutes: (state) => state.addedRoutes
    },

    // 动作，包含异步操作和状态更新
    actions: {
        /**
         * 获取用户信息
         * @param id 用户ID
         */
        async fetchUserInfo(id: number) {
            this.loading = true;
            try {
                const response = await getUserInfoApi({ id });
                if (response.code !== 200) {
                    throw new Error(response.message || '获取用户信息失败');
                }
                this.user = response.result;
                sessionStorage.setItem("user", JSON.stringify(response.result))
                return response.result;
            } catch (error: any) {
                throw new Error(error.message || '获取用户信息失败');
            } finally {
                this.loading = false;
            }
        },

        /**
         * 获取用户列表
         * @param params 列表参数
         */
        async fetchUserList(params: ListParams) {
            this.loading = true;
            try {
                const response = await getUserListApi(params);
                if (response.code !== 200) {
                    throw new Error(response.message || '获取用户列表失败');
                }
                this.userList = response.result;
                return response.result;
            } catch (error: any) {
                throw new Error(error.message || '获取用户列表失败');
            } finally {
                this.loading = false;
            }
        },

        /**
         * 更新用户信息
         * @param user 用户信息
         */
        async updateUserInfo(user: User) {
            this.loading = true;
            try {
                const response = await updateUserInfoApi(user);
                if (response.code !== 200) {
                    throw new Error(response.message || '更新用户信息失败');
                }
                // 更新本地用户信息
                this.user = { ...this.user, ...user };
                return response.result;
            } catch (error: any) {
                throw new Error(error.message || '更新用户信息失败');
            } finally {
                this.loading = false;
            }
        },

        /**
         * 上传用户头像
         * @param file 头像文件
         */
        async uploadAvatar(file: File) {
            this.loading = true;
            try {
                const formData = new FormData();
                formData.append('file', file);
                const response = await uploadUserAvatarApi(formData);
                if (response.code !== 200) {
                    throw new Error(response.message || '上传头像失败');
                }
                const avatarUrl = response.result.avatarUrl;
                this.user.avatarUrl = avatarUrl;
                return avatarUrl;
            } catch (error: any) {
                throw new Error(error.message || '上传头像失败');
            } finally {
                this.loading = false;
            }
        },

        /**
         * 设置是否添加了动态路由
         * @param added 是否添加
         */
        setAddedRoutes(added: boolean) {
            this.addedRoutes = added;
        }
    }
});